package com.yangbo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Administrator
 * @Date 2018-10-15 11:26
 */
@Component
public class ZuulGatewayFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(ZuulGatewayFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            log.warn("token is empty");
            //限制其进行路由
            context.setSendZuulResponse(false);
            //设置相应状态码
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            context.getResponse().setContentType(MediaType.APPLICATION_JSON.getType());
            try {
                PrintWriter writer = context.getResponse().getWriter();
                writer.append("{");
                writer.append("\"code\":401,");
                writer.append("\"msg\":\"token is empty\"");
                writer.append("}");
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        log.info("ok");
        return null;
    }
}
